package com.eight.cloud.admin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eight.cloud.admin.entity.RoleEntity;
import com.eight.cloud.admin.entity.RolePermissionEntity;
import com.eight.cloud.admin.mapper.RolePermissionMapper;
import com.eight.cloud.admin.service.IRolePermissionService;
import com.eight.cloud.mybatisplus.service.BaseService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色-权限表 服务实现类
 * </p>
 *
 * @author TXC
 * @since 2024-10-02
 */
@Service
public class RolePermissionServiceImpl extends BaseService<RolePermissionMapper, RolePermissionEntity> implements IRolePermissionService {

    @Override
    public void flush(RoleEntity role, List<String> permissionCodes) {
        List<RolePermissionEntity> rolePermissionList =
                baseMapper.selectList(lambdaQueryWrapper().eq(RolePermissionEntity::getRoleId
                        , role.getUuid()));
        Map<String, RolePermissionEntity> rolePermissionMap =
                rolePermissionList.stream().collect(Collectors.toMap(RolePermissionEntity::getPermissionCode, e -> e));
        permissionCodes.forEach(permissionCode -> {
            RolePermissionEntity roleDept = rolePermissionMap.get(permissionCode);
            if (ObjectUtil.isNotNull(roleDept)) {
                rolePermissionMap.remove(permissionCode);
            } else {
                RolePermissionEntity permissionEntity = new RolePermissionEntity();
                permissionEntity.setRoleId(role.getUuid());
                permissionEntity.setPermissionCode(permissionCode);
                permissionEntity.setTenantId(role.getTenantId());
                baseMapper.insert(permissionEntity);
            }
        });
        rolePermissionMap.forEach((k, v) -> baseMapper.delete(lambdaQueryWrapper().eq(RolePermissionEntity::getUuid, v.getUuid())));
    }

    @Override
    public void delExcludePermission(List<String> permissionCodes) {
        if (ObjectUtil.isNotEmpty(permissionCodes)) {
            baseMapper.delExcludePermission(permissionCodes);
        }
    }

    @Override
    public void truncate() {
        baseMapper.truncate();
    }

    @Override
    public List<RolePermissionEntity> getRolePermissionList(String roleId) {
        return baseMapper.selectList(lambdaQueryWrapper().eq(RolePermissionEntity::getRoleId, roleId));
    }

    @Override
    public List<RolePermissionEntity> getRolePermissionList(String permissionCode, List<String> roleIds) {
        return baseMapper.selectList(Wrappers.<RolePermissionEntity>lambdaQuery()
                .eq(RolePermissionEntity::getPermissionCode, permissionCode)
                .in(RolePermissionEntity::getRoleId, roleIds));
    }
}
